/*
 * Copyright 2021-2022 Alibaba Group Holding Ltd.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.aliyun.fastmodel.converter.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * GenericTypeUtil
 *
 * @author panguanjing
 * @date 2021/6/14
 */
public class GenericTypeUtil {
    public static Class getSuperClassGenericType(Class clazz, int index)
        throws IndexOutOfBoundsException {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class)params[index];
    }

    public static Class getSuperInterfaceGenericType(Class clazz, int index)
        throws IndexOutOfBoundsException {
        Type[] params = clazz.getGenericInterfaces();
        if (params.length == 0) {
            return Object.class;
        }
        Type genType = params[0];
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        ParameterizedType parameterizedType = (ParameterizedType)genType;
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        if (index >= actualTypeArguments.length || index < 0) {
            return Object.class;
        }
        if (!(actualTypeArguments[index] instanceof Class)) {
            return Object.class;
        }
        return (Class)actualTypeArguments[index];
    }
}
